import router from "@src/router";
import member from '@src/store/member'
import base from '@src/store/base'
import mall from '@src/store/mall'
import location from '@src/store/location'
import dianpufenlei from '@src/store/dianpufenlei'

import {
	dumpFunc
} from '@src/common/dump'
import {
	getNearStore,
	getStoreDetail,
	getQrcodeMsg
} from '@src/api/mall/store'
import {getPopWindow,recordCustomerPop} from '@src/api/pop'
// import { getNearStore,getQrcodeMsg,getStoreDetail } from '@src/api/mall/store'


import {
	storeBindingsBehavior
} from 'mobx-miniprogram-bindings'
import {
	getUrlQueryString
} from "@src/common/utils";
import $cache from '@src/common/wxCache'

Component({
	behaviors: [storeBindingsBehavior],
	storeBindings: [{
			store: base,
			fields: ['isInit', 'themeCode', 'businessName', 'businessLogo',
				'statusBarHeight', 'navBarHeight', 'themeTitleColor', 'themeColor', "homePage",
				'splashScreen'
			],
			actions: {
				getThemeConfig: 'themeConfig',
				initReady: 'initReady',
				setIndexPageScene: 'setIndexPageScene'
			}
		},
		{
			store: member,
			fields: ['isMember', 'categoryImage', 'name', 'cardOrder'],
			actions: ['getBaseInfo'],
		}, {
			store: mall,
			fields: ['curLocation', 'storeId'],
			actions: ['initLocation', 'setAddress', 'setStoreId']
		},
		{
			store: location,
			fields: ['auth', 'ask']
		},
		{
			store: dianpufenlei,
			fields: ['hasDianpujianjie'],
			actions: {
				getStoreGoodsList: 'getStoreGoodsList',
				getFetchData: 'getFetchData',
				setPageScrollTop: 'setPageScrollTop',
				setTop: 'setTop',
				initChange: 'initChange'
			}
		}
	],
	data: {
		cardImg: '/wxapp/static/index/i-ka.png',
		shareImg: '',
		availableData: null,
		shareTitle: '邀请你注册成为会员',
		loading: true,
		navLoading: false,
		//倒计时
		countDownTime: 0,
		//存储定时器
		setInter: "",
		login: false,
		storeInfo: null,
		isShow: true,
		pageId: null,
		showGuide: false,
		// 弹窗数据
		pops: {},
		showSuspend: true,
		showAd: false,
		token: $cache.get("token"),
		baseUrl: '',
		showStartPage:true
	},
	observers: {
		'isInit': function(isInit) {
			if (isInit) {
				clearInterval(this.data.setInter)
				this.getTabBar().show();

			} else {
				this.getTabBar().hide();
			}
		},
		'curLocation': function(curLocation) {
			if (!curLocation || this.data.loading) {
				return;
			}
			let temp = {
				latitude: curLocation.latitude,
				longitude: curLocation.longitude
			}
			this.getNearStoreFunc(temp)
		},
		'storeId': function(storeId) {
			if (!storeId) return
			// 弹窗
			// this.fetchData()
			this.getStoreDetail()	
		
		}
	},
	methods: {
		onLoad(options) {
			console.log('this.data.token',this.data.token);
			this.setData({baseUrl: getApp().globalData.extConfig.fileBaseUrl })
			let scene = "";
			let receiveWay = "";
			if (options && options.scene) {
				if (decodeURIComponent(options.scene) && !options.receiveWay) {
					scene = decodeURIComponent(options.scene);
				} else if (options.receiveWay) {
					// 微信分享
					scene = options.scene;
					receiveWay = options.receiveWay;
				} else if (options.path) {
					// 线下
					scene = getUrlQueryString("scene")
				}
			}
			if (options && options.q) {
				this.setData({showStartPage:false})
				const q = decodeURIComponent(options.q)
				let codeNo = q.split('/')[q.split('/').length - 1]
				let isDiscounts = codeNo.indexOf('_')
				clearInterval(this.data.setInter)
				this.getTabBar().hide();
				
				// 通过桌码进来的
				if (isDiscounts == -1) {
					getQrcodeMsg({
						codeNo
					}).then((res) => {
						let {
							data
						} = res
						data.bizData = JSON.parse(data.bizData)
						let ceterPath = 'catering/pages/index/main'
						if (data.dumpPath.indexOf(ceterPath) != -1) {
							if (data && data.bizData && data.bizData.id) {
								getApp().globalData.dinnerType = 0
								getApp().globalData.dinnerShopid = ''
								getApp().globalData.dinnerTabNum = ''
								router.push({
									name: 'codeorder/index',
									params: {
										deskId: data.bizData.id,
										shopId: res.data.bizShopId
									},
								})
							}
						} else {
							router.push({
								path: data.dumpPath,
								params: data,
							})
						}
					})
				} else if (isDiscounts != -1 && codeNo.indexOf('cd') != -1) {
					// 跳转卡页面

				} else if (isDiscounts != -1 && codeNo.indexOf('cp') != -1) {
					// 跳转优惠券页面

				}

			}
			console.info("scene, receiveWay", scene, receiveWay)
			this.setIndexPageScene(scene, receiveWay);  
			// 弹窗
			// console.log('this.data.token222',this.data.token);
			// if (this.data.token) {
			//     this.fetchData()
		    // }
		},
		onShow() {
			wx.removeStorageSync('Private_Domain_Meal_Method')
			const appOps = wx.getEnterOptionsSync()
			//公众号引导场景值
			let guideScenes = [1011, 1017, 1025, 1047, 1124]
			this.setData({
				showGuide: guideScenes.includes(appOps.scene)
			})
			this.setData({
				pageId: null
			})
			let tabParams = JSON.parse(JSON.stringify(getApp().globalData.tabParams))
			if (tabParams) {
				getApp().globalData.tabParams = null
				let pageId = tabParams.split('=')[1]
				this.setData({
					pageId
				})
			}
			this.getTabBar().select("pages/index/main")
			this.setData({
				isShow: true,
				showStartPage:true
			})
			// console.log('检查登录态')
			// this.selectComponent("#login")._login();
			
		},
		onHide() {
			this.setData({
				isShow: false
			})
		},
		onLogin() {
			
			this.updateStoreBindings();
			this.setData({
				login: true,
				loading: false
			});
			this.fetchData()
			this.getFetchData(this.data.homePage)
			this.getNearStoreFunc()
		},
		onPageScroll(e) {
			if (!this.data.hasDianpujianjie) return
			const {
				storeAboutQuery
			} = getApp().globalData
			if (!storeAboutQuery) return
			storeAboutQuery.then(query => {
				query.exec((res) => {
					let storeAboutHeight = res[0].height
					if (e.scrollTop > (storeAboutHeight - 150) && e.scrollTop < (
							storeAboutHeight + 150)) {
						this.setTop(e.scrollTop >= storeAboutHeight, storeAboutHeight)
					}
				})
			})
		},
		onReachBottom() {
			this.getStoreGoodsList()
		},
		onShareAppMessage() {
			let homePageConfig = this.data.homePage.config;
			let data = {
				path: `pages/index/main`
			}
			if (homePageConfig.shareTitle) {
				data['title'] = homePageConfig.shareTitle;
			} else {
				data['title'] = this.data.businessName;
			}
			if (homePageConfig.shareImageUrl) {
				data['imageUrl'] = homePageConfig.shareImageUrl;
			}
			return data;
		},
		getNearStoreFunc(temp) {
			if (temp && !this.data.login) return
			let self = this;
			getNearStore(temp).then(res => {
				if (res.code === 0 && res.data) {
					self.setStoreId(res.data.storeId);
					self.updateStoreBindings();
				}
			})
		},
		getStoreDetail() {
			getStoreDetail({
					storeId: this.data.storeId
				})
				.then(res => {
					this.setData({
						storeInfo: res.data
					})
				})
		},
		jumpAddress() {
			const a = function acceptDataFromOpenedPage(data) {
				this.setAddress(data.address);
				this.updateStoreBindings();
			};
			router.push({
				name: 'mall/address',
				events: {
					// 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
					acceptDataFromOpenedPage: (data) => {
						this.setAddress(data.address);
						this.updateStoreBindings();
					},
				},
			})
		},
		onPullDownRefresh() {
			this.getThemeConfig();
			// await this.getConfig();
			wx.stopPullDownRefresh();

		},
		dumpPage(e) {
			let item = e.currentTarget.dataset.item;
			if (item && item[0].dump) {
				dumpFunc(item[0].dump, item[0].biz)
			}
		},
		onAnon() {
			this.updateStoreBindings();
			this.setData({
				login: false,
				loading: false
			});
			this.fetchData()
			this.getNearStoreFunc()
			// console.log('2222daioyognle');
		},
		handleLogin() {
			const loginComp = this.selectComponent("#login");
			loginComp.requireLogin();
		},
        
		fetchData() {
				getPopWindow().then(res => {
					console.log('res25', res);
					if (res.data.popType === 1) {
						res.data.appImgUrl = res.data.appImgUrl + "?x-oss-process=image/resize,m_pad,h_800,w_600,color_FFFFFF"
					}
					res.data.overUrl=res.data.overUrl+"?x-oss-process=image/resize,m_pad,h_103,w_103,color_FFFFFF"
					
					this.setData({
					  pops:res.data
					})
					console.log('pops', this.data.pops);
					res.data.imageUrl
					// 如果返回null就不显示弹窗
					if (res.data === null) {
					  this.setData({
						showSuspend:true,
						showAd:true,
					  })
					} else {
					  this.setData({
						showAd:false,
					  })
						console.log(20220913, this.data.login);
						
						if (this.data.login) {
						this.setData({showAd:!this.data.showSuspend})
					}
					// 记录用户最后弹窗时间
					if(this.data?.pops?.popId) {
						recordCustomerPop({popId:this.data.pops.popId}).then(res => {
						})
					}
					
				    } 
				})
		  },
		// 取消弹窗
		handleCancelPop() {
			console.log('触发了');
			this.setData({ showAd: !this.data.showAd });
			if (this.data.pops.isOver === true) {
				if (this.data.showAd === true) {
					this.setData({ showSuspend: false })
			  }
			}
		},
		handelCancelSm() {
			this.setData({ showSuspend: !this.data.showSuspend });
		},
		showAdImgEvent() {
			this.setData({ showAd:false,showSuspend:true });
		},
	}
})
